<?php

class ReportController extends Controller {
    const PAGE_SIZE=10;
	
    const CONTROLLER_ID = 1;

    public $defaultAction = "create";
    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
        	'accessControl', // perform access control for CRUD operations
            'postOnly + addcargo,removecargo'
        );
    }
	
    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
        	array('allow',  // allow all users to perform 'index' and 'view' actions
        		'actions'=>array(''),
        		'users'=>array('*'),
        	),
        	array('allow', // allow authenticated user to perform 'create' and 'update' actions
        		'actions'=>array('create','report','view','addcargo','generate','list'),
        		'users'=>array('@'),
        	),
        	array('allow', // allow admin user to perform 'admin' and 'delete' actions
        		'actions'=>array('admin'),
        		'users'=>array('admin'),
        	),
        	array('deny',  // deny all users
        		'users'=>array('*'),
        	),
        );
    }

    /**
     * Displays a particular model.
     */
     public function actionCreate(){
         $model = new report;

         if(isset($_POST['Report'])) {
             $model->attributes = $_POST['Report'];
             $this->validateModels($model);
             $ajax = (isset($_POST['ajax']) && $_POST['ajax']==='report-form' && Yii::app()->request->isAjaxRequest)?true:false;
             $transaction = Yii::app()->db->beginTransaction();
            try{
            	if(!$model->save())
                    throw new Exception('Report saving error');
            	$transaction->commit();
            	if($ajax){
            		echo CJavaScript::jsonEncode(array('id'=>$model->id));
            		Yii::app()->end();
            	}
            	else
            		$this->redirect(array('view','id'=>$model->id));
            }
            catch(Exception $e) {
            	$transaction->rollback();
            	if($ajax){
            		echo CJavaScript::jsonEncode(array('formerror'=>$e->getMessage()));
            		Yii::app()->end();
            	}
            }

         }
         $this->render('create',array('model'=>$model));
     }

     public function actionGenerate(){
        $model = $this->loadModel();
        $pdf = new makePdf;
        $pdf->setSize('A4', 'L');
        $dataProvider = new CArrayDataProvider($model->cargo, array(
            'sort'=>array(
                'defaultOrder'=>'import_date'
            ),
        ));
        $pagination = new CPagination($model->cargoCount);
        $pagination->setPageSize(10);
        for($i=0;$i<=$pagination->getPageCount()-1;$i++){
            $pagination->setCurrentPage($i);
            $dataProvider->setPagination($pagination);
            $pdf->renderPartial('MES', array('model'=>$model,'dataProvider'=>$dataProvider,'pagination'=>$pagination));
        }
        $pdf->stream('MES');
     }

     public function actionList(){
        $model = new report;
        $this->render('list',array('model'=>$model));
     }

     public function actionAddCargo(){
        $model = $this->loadModel();
        $model->cargo_id = $_GET['cargo_id'];
        $model->setScenario('addCargo');
        $return = $model->addCargo();
        if(Yii::app()->request->isAjaxRequest){
            if(!$return)
                echo CJSON::encode(array('formerror'=>'Unable to add cargo','notificationError'=>'Unable to add cargo'));
            Yii::app()->end();
        }
        else
            $this->redirect(array('view','id'=>$model->id));
     }

     public function actionRemoveCargo(){
         $model = $this->loadModel();
         $model->cargo_id = $_GET['cargo_id'];
         $return = $model->removeCargo();
         if(Yii::app()->request->isAjaxRequest){
            if(!$return)
                echo CJSON::encode(array('formerror'=>'Unable to remove cargo','notificationError'=>'Unable to remove cargo'));
            Yii::app()->end();
        }
        else
            $this->redirect(array('view','id'=>$model->id));
     }

     public function actionView(){
         $model = $this->loadModel();
         $cargo = new cargo;
         if(isset($_GET['searchText']))
             $cargo->marking = $_GET['searchText'];
         $this->render('view',array('model'=>$model,'cargo'=>$cargo));
     }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     */
    public function loadModel() {
        if($this->_model===null) {
            if(isset($_GET['id']))
                $this->_model=report::model()->findbyPk($_GET['id']);
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $this->_model;
    }
}
